/**
 * 	 DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *   @author Colin Redmond
 *   Copyright (C) 2011 Colin Redmond
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

package com.cred.industries.platform.resources;

import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cred.industries.core.exceptions.ApplicationException;
import com.cred.industries.core.util.ExceptionResponse;
import com.cred.industries.platform.business.facade.SessionFacade;
import com.cred.industries.platform.business.objects.SessionBO;
import com.cred.industries.platform.defines.Role;
import com.cred.industries.platform.transferObj.SessionResultTrans;
import com.sun.jersey.api.core.HttpContext;

@Path("/session")
public class SessionRes {
	private static final Logger logger = LoggerFactory.getLogger(SessionRes.class);
	
	/**
	 * Creates a session that is stored in the DB. Permits all roles, since we get the roles  
	 * from a session, so without a session we cant have a role
	 * @param hc Contains all information to authenticate user. 
	 * @return the session key
	 * @throws WebApplicationException, used by jersey to build a responce for the clients
	 */
	@POST
	@Produces(MediaType.APPLICATION_XML)
	@PermitAll
	public SessionResultTrans createSession(@Context HttpContext hc) {

		try {
			SessionBO sessionBO;
			SessionFacade sessionF = new SessionFacade();
			sessionBO = sessionF.createSession(hc);
			String sessionId = "";
			if(sessionBO != null) {
				sessionId = sessionBO.getSessionId();
			} else {
				throw new WebApplicationException(ExceptionResponse.build(Status.INTERNAL_SERVER_ERROR));
			}
			
			SessionResultTrans result = new SessionResultTrans(sessionId, sessionBO.getCustomerId());
			
			return result;
		} catch (ApplicationException | WebApplicationException e) {
			logger.error("Exception " + e.toString() + " " + e.getMessage());
			e.printStackTrace();
			throw e;
		} catch (Throwable e) {
			logger.error("Exception " + e.toString() + " " + e.getMessage());
			e.printStackTrace();
			throw new WebApplicationException(ExceptionResponse.build(e));
		} 
	}
	
	/**
	 * Deletes a session key when the user logs off
	 * @param key the session key we wish to delete
	 * @return if we are successful or not
	 * @throws WebApplicationException, used by jersey to build a responce for the clients
	 */
	@DELETE
	@Path("/{key}")
	@Consumes(MediaType.TEXT_PLAIN)
	@Produces(MediaType.TEXT_PLAIN)
	@RolesAllowed({Role.ADMIN_STRING, Role.CS_STRING, Role.USER_STRING })
	public Response deleteSession(@PathParam("key") String key) {

		try {
			SessionFacade sessionF = new SessionFacade();
			sessionF.deleteSession(key);
			

			ResponseBuilder response = Response.status(Status.ACCEPTED);
			response.type(MediaType.TEXT_PLAIN);

			return response.build();
		} catch (ApplicationException | WebApplicationException e) {
			logger.error("Exception " + e.toString() + " " + e.getMessage());
			e.printStackTrace();
			throw e;
		} catch (Throwable e) {
			logger.error("Exception " + e.toString() + " " + e.getMessage());
			e.printStackTrace();
			throw new WebApplicationException(ExceptionResponse.build(e));
		} 
	}

}
